import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_shop/eventbus/event_bus.dart';
import 'package:flutter_shop/pages/cart/cart_cons.dart';
import 'package:flutter_shop/pages/cart/cart_tab_page/cart_tab_page.dart';
import 'package:flutter_shop/pages/cart/cart_tab_page/entity/cart_goods_data.dart';
import 'package:flutter_shop/pages/home/goods_detail/entity/goods_detail_data.dart';
import 'package:flutter_shop/utils/log_utils.dart';
import 'package:flutter_shop/utils/sp_util.dart';
import 'package:flutter_shop/utils/utils.dart';

///购物车提供者
class CartProvider with ChangeNotifier {
  static const String TAG = "CartProvider";

  ///购物车商品列表
  List<CartGoodsData> cartGoodsList = [];

  ///商品总价
  double totalPrice = 0;

  ///商品总数量
  int totalCount = 0;

  ///是否全选
  bool isCheckAll = true;

  ///获取购物车商品列表
  void getCartGoodsList() {
    //取本地购物车商品
    cartGoodsList.clear();
    cartGoodsList.addAll(_getLocalCartGoodsList());

    //计算总价,总数,是否全选
    _computeTotalPriceAndTotalCountAndIsCheckAll();
  }

  ///添加商品
  void add(GoodsDetailDataGoodInfo goodInfo) {
    //取本地购物车商品
    List<CartGoodsData> tempList = _getLocalCartGoodsList();
    //比对状态管理存的列表
    if (tempList.length != cartGoodsList.length) {
      cartGoodsList.clear();
      cartGoodsList.addAll(tempList);
    }

    //遍历商品,看要添加的商品是否存在
    bool isExist = false;

    for (CartGoodsData v in cartGoodsList) {
      //已存在商品,数量+1
      if (v.goodsId == goodInfo.goodsId) {
        v.count = v.count + 1;
        isExist = true;
        break;
      }
    }

    //不存在,就添加
    if (!isExist) {
      CartGoodsData cartGoodsEntity = new CartGoodsData();
      cartGoodsEntity.goodsId = goodInfo.goodsId;
      cartGoodsEntity.goodsName = goodInfo.goodsName;
      cartGoodsEntity.count = 1;
      cartGoodsEntity.price = goodInfo.presentPrice;
      cartGoodsEntity.oriPrice = goodInfo.oriPrice;
      cartGoodsEntity.image = goodInfo.image1;
      cartGoodsEntity.checked = true;
      cartGoodsList.add(cartGoodsEntity);
    }

    //计算总价,总数,是否全选
    _computeTotalPriceAndTotalCountAndIsCheckAll();

    //存本地购物车商品
    SpUtil.putObjectList(CartCons.KEY_CART_GOODS_LIST, cartGoodsList);

    Log.obj(cartGoodsList, tag: TAG);

    notifyListeners();
  }

  ///清空购物车
  void clear() {
    SpUtil.remove(CartCons.KEY_CART_GOODS_LIST);
    cartGoodsList.clear();

    //计算总价,总数,是否全选
    _computeTotalPriceAndTotalCountAndIsCheckAll();

    notifyListeners();
  }

  ///删除购物车商品
  void deleteById(String goodsId) {
    List<CartGoodsData> tempList = _getLocalCartGoodsList();

    //比对状态管理存的列表
    if (tempList.length != cartGoodsList.length) {
      cartGoodsList.clear();
      cartGoodsList.addAll(tempList);
    }

    int delIndex;
    for (int i = 0; i < cartGoodsList.length; i++) {
      CartGoodsData item = cartGoodsList[i];
      if (item.goodsId == goodsId) {
        delIndex = i;
        break;
      }
    }
    if (delIndex != null) {
      cartGoodsList.removeAt(delIndex);
    }

    //计算总价,总数,是否全选
    _computeTotalPriceAndTotalCountAndIsCheckAll();

    //存本地购物车商品
    SpUtil.putObjectList(CartCons.KEY_CART_GOODS_LIST, cartGoodsList);

    if (cartGoodsList.isEmpty) {
      EventBus().post(EventMessage(CartTabPage.SHOW_EMPTY));
    }

    notifyListeners();
  }

  ///选择item
  void checkItem(String goodsId) {
    List<CartGoodsData> tempList = _getLocalCartGoodsList();

    //比对状态管理存的列表
    if (tempList.length != cartGoodsList.length) {
      cartGoodsList.clear();
      cartGoodsList.addAll(tempList);
    }

    for (int i = 0; i < cartGoodsList.length; i++) {
      CartGoodsData item = cartGoodsList[i];
      if (item.goodsId == goodsId) {
        item.checked = !item.checked;
        break;
      }
    }

    //计算总价,总数,是否全选
    _computeTotalPriceAndTotalCountAndIsCheckAll();

    //存本地购物车商品
    SpUtil.putObjectList(CartCons.KEY_CART_GOODS_LIST, cartGoodsList);

    notifyListeners();
  }

  ///选择所有
  void checkAll(bool isCheckAll) {
    cartGoodsList.forEach((item) {
      item.checked = isCheckAll;
    });

    this.isCheckAll = isCheckAll;

    //计算总价,总数,是否全选
    _computeTotalPriceAndTotalCountAndIsCheckAll();

    //存本地购物车商品
    SpUtil.putObjectList(CartCons.KEY_CART_GOODS_LIST, cartGoodsList);

    notifyListeners();
  }

  ///购物车加减操作
  ///isIncr true:加 false:减
  void incrOrDecr(String goodsId, bool isIncr) {
    List<CartGoodsData> tempList = _getLocalCartGoodsList();

    //比对状态管理存的列表
    if (tempList.length != cartGoodsList.length) {
      cartGoodsList.clear();
      cartGoodsList.addAll(tempList);
    }

    for (int i = 0; i < cartGoodsList.length; i++) {
      CartGoodsData item = cartGoodsList[i];
      if (item.goodsId == goodsId) {
        if (isIncr) {
          item.count++;
        } else {
          if (item.count > 1) {
            item.count--;
          } else {
            Utils.showToast("不能再减少了");
          }
        }
        break;
      }
    }

    //计算总价,总数,是否全选
    _computeTotalPriceAndTotalCountAndIsCheckAll();

    //存本地购物车商品
    SpUtil.putObjectList(CartCons.KEY_CART_GOODS_LIST, cartGoodsList);

    notifyListeners();
  }

  ///获取本地购物车
  List<CartGoodsData> _getLocalCartGoodsList() {
    return SpUtil.getObjList<CartGoodsData>(CartCons.KEY_CART_GOODS_LIST, (v) => CartGoodsData().fromJson(v), defValue: []);
  }

  ///计算总价,总数,是否全选
  void _computeTotalPriceAndTotalCountAndIsCheckAll() {
    int count = 0;
    double price = 0.0;
    bool isCheckAll = true;

    cartGoodsList.forEach((item) {
      if (item.checked) {
        //总数
        count += item.count;
        //总价
        double itemPrice = NumUtil.multiply(item.count, item.price);
        price = NumUtil.add(price, itemPrice);
      } else {
        isCheckAll = false;
      }
    });

    this.totalCount = count;
    this.totalPrice = price;
    this.isCheckAll = isCheckAll;
  }
}
